package com.common.android.utils.httpRequest;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Proxy;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import com.common.android.utils.MD5ArithmeticUtils;
import com.common.android.utils.http.HttpEntityDelete;
import com.common.android.utils.http.SSLSocketFactoryEx;
import com.nd.android.u.allcommon.R;


/**
 * @ClassName: HttpRequest
 * @Description: HTTP通讯基类
 * @author Administrator
 * @date 2012-2-1 上午09:50:25
 */
public class HttpRequest implements IHttpRequest {
	protected String TAG = "HttpRequest";

	public final static String GZIP = "gzip";

	public final static String ACCEPT_ENCODEING = "Accept-Encoding";

	private final int CONNECTION_TIMEOUT_MS = 20000; // 20秒

	private final int SOCKET_TIMEOUT_MS = 60000;// 60秒

	private static IHttpRequest mHttp;

	protected static Context mContext;

	private String mSid = "";
	
	public static IHttpRequest getInstance(Context ctx) {
		if (mHttp == null) {
			mHttp = new HttpRequest(ctx);
		}
		return mHttp;
	}

	public HttpRequest(Context ctx) {
		if(ctx!=null)
		{
		mContext = ctx.getApplicationContext();
		}
	}

	public void setSid(String sid){
		mSid = sid;
	}
	/**
	 * @n<b>添加自定义头</b> :setHttpHeader
	 * @brief
	 * @see
	 * @param @param request
	 * @return void
	 * @<b>作者</b> : yanyy
	 * @<b>创建时间</b> : 2011-10-14下午04:04:09
	 */
	public void setHttpHeader(HttpRequestBase request) {
		request.addHeader(ACCEPT_ENCODEING, GZIP);
		if(!TextUtils.isEmpty(mSid)){
			request.addHeader(new BasicHeader("COOKIE", "PHPSESSID="	+ mSid));
		}
	}
    /**
     * Setup HTTPConncetionParams
     * 设置HTTP的连接参数,超时时间，重试，异常处理
     */
    protected void setupHTTPConnectionParams(HttpUriRequest method) {
        HttpConnectionParams.setConnectionTimeout(method.getParams(),CONNECTION_TIMEOUT_MS);
        HttpConnectionParams.setSoTimeout(method.getParams(), SOCKET_TIMEOUT_MS);
        //设置异常自动处理
//        mClient.setHttpRequestRetryHandler(requestRetryHandler);        
        method.addHeader("Accept-Encoding", GZIP);
        method.addHeader(new BasicHeader("COOKIE", "PHPSESSID="	+ mSid + ""));
//        Log.d(TAG,"PHPSESSID="	+ sid + "");
    }
	@Override
	public int doDelete(String mStrURL, StringBuilder receive) {
		debug( "dodelete:"+mStrURL);
		int nRet = R.string.nd_http_error;
		InputStream inputStream = null;
		receive.delete(0, receive.length());
		try {
			// make a DELETE client
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					CONNECTION_TIMEOUT_MS);
			HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT_MS);
			HttpClientParams.setRedirecting(httpParams, true);
			HttpClient client = getNewHttpClient(httpParams);

			// 检查代理设置
//			checkProxy(client);

			HttpDelete request = new HttpDelete(mStrURL);

			setHttpHeader(request);

			// POST and get response code
			HttpResponse response = client.execute(request);
			nRet = response.getStatusLine().getStatusCode();
			// get response string
			inputStream = response.getEntity().getContent();

			Header contentEncoding = response
					.getFirstHeader(HTTP.CONTENT_ENCODING);
			// 判断是否有压缩
			if (contentEncoding != null
					&& contentEncoding.getValue().equalsIgnoreCase(GZIP)) {
				inputStream = new GZIPInputStream(inputStream);
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(
					inputStream));

			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				receive.append(line + NL);
			}

			if (nRet == HttpStatus.SC_OK || nRet == HttpStatus.SC_CREATED) {

			} else {
				if (receive.length() <= 0)
					receive.append(response.getStatusLine().getReasonPhrase());
				if (receive.length() > 0)
					Log.v(TAG, receive.toString());
				Log.v(TAG, "nRet=" + nRet + ", url = " + mStrURL);
			}
		} catch (SocketTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_timeout_error;
		} catch (SocketException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_error;
		} catch (ConnectTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_connect_timeout_error;
		} catch (UnknownHostException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_unknown_host_error;
		} catch (Exception e) {
			Log.e(TAG, getErrMsg(e));
			receive.append(getErrMsg(e));
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException ioe) {
					Log.e(TAG, ioe.toString());
				}
			}
		}

		return nRet;
	}
	/**
	 * 获取支持http请求的client
	 * 
	 * <br>Created 2014-9-25 上午10:04:26
	 * @return
	 * @author       jiaoyun
	 */
	private HttpClient getHttpClient() {
		// make a DELETE client
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams,
				CONNECTION_TIMEOUT_MS);
		HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT_MS);
		HttpClientParams.setRedirecting(httpParams, true);
		HttpClient client = getNewHttpClient(httpParams);
		return client;
	}
	/**
	 * 获取支持https请求的Client  异常要向上抛出，以便发生异常时，可以通过Http请求进行登录
	 * 
	 * <br>Created 2014-9-25 上午10:04:56
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws CertificateException
	 * @throws IOException
	 * @throws KeyStoreException
	 * @throws KeyManagementException
	 * @throws UnrecoverableKeyException
	 * @author       jiaoyun
	 */
	private HttpClient getHttpsClient() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, KeyManagementException, UnrecoverableKeyException{
		  

		 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
		
	        trustStore.load(null, null); 
	        SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);  
	        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 
	        HttpParams params = new BasicHttpParams();

//	        //设置每个连接最大的自然连接数
	        ConnManagerParams.setMaxTotalConnections(params, 100);
	        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
	    	HttpProtocolParams.setContentCharset(params,
					HTTP.UTF_8);
			HttpProtocolParams.setUseExpectContinue(params, true);
			HttpConnectionParams.setConnectionTimeout(params,
					CONNECTION_TIMEOUT_MS);
			HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT_MS);
	        SchemeRegistry schemeRegistry = new SchemeRegistry();
	        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
	        schemeRegistry.register(new Scheme("https", sf, 443));
	        ClientConnectionManager conManager = new ThreadSafeClientConnManager(
					params, schemeRegistry);
	        return new DefaultHttpClient(conManager, params);
	
	}

	@Override
	public int doGet(String mStrURL, StringBuilder receive) {
		debug("doGet:"+ mStrURL);
		int nRet = R.string.nd_http_error;
		InputStream inputStream = null;
		receive.delete(0, receive.length());
		try {
			HttpClient client = getHttpClient();

			// 检查代理设置
//			checkProxy(client);

			HttpGet request = new HttpGet();
			request.setURI(new URI(mStrURL));

			setHttpHeader(request);

			// sending request
			HttpResponse response = client.execute(request);
			nRet = response.getStatusLine().getStatusCode();

			// get response code and string
			inputStream = response.getEntity().getContent();
			Header contentEncoding = response
					.getFirstHeader(HTTP.CONTENT_ENCODING);
			// 判断是否有压缩
			if (contentEncoding != null
					&& contentEncoding.getValue().equalsIgnoreCase(GZIP)) {
				inputStream = new GZIPInputStream(inputStream);
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(
					inputStream));
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				receive.append(line + NL);
			}

			if (nRet == HttpStatus.SC_OK || nRet == HttpStatus.SC_CREATED) {

			} else {
				if (receive.length() <= 0)
					receive.append(response.getStatusLine().getReasonPhrase());
				if (receive.length() > 0)
					Log.v(TAG, receive.toString());
				Log.v(TAG, "nRet=" + nRet + ", url = " + mStrURL);
			}

		} catch (SocketTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_timeout_error;
		} catch (SocketException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_error;
		} catch (ConnectTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_connect_timeout_error;
		} catch (UnknownHostException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_unknown_host_error;
		} catch (Exception e) {
			Log.e(TAG, getErrMsg(e));
			receive.append(getErrMsg(e));
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException ioe) {
					Log.e(TAG, ioe.toString());
				}
			}
		}

		return nRet;
	}
	
	@Override
	public int doGetGBK(String mStrURL, StringBuilder receive) {
		debug("doGetGBK:"+ mStrURL);
		int nRet = R.string.nd_http_error;
		InputStream inputStream = null;
		receive.delete(0, receive.length());
		try {
			HttpClient client = getHttpClient();

			// 检查代理设置
//			checkProxy(client);

			HttpGet request = new HttpGet();
			request.setURI(new URI(mStrURL));

			setHttpHeader(request);

			// sending request
			HttpResponse response = client.execute(request);
			nRet = response.getStatusLine().getStatusCode();
			
			// get response code and string
			inputStream = response.getEntity().getContent();
			Header contentEncoding = response
					.getFirstHeader(HTTP.CONTENT_ENCODING);
			// 判断是否有压缩
			if (contentEncoding != null
					&& contentEncoding.getValue().equalsIgnoreCase(GZIP)) {
				inputStream = new GZIPInputStream(inputStream);
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(
					inputStream, "GB2312"));
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				receive.append(line + NL);
			}

			if (nRet == HttpStatus.SC_OK || nRet == HttpStatus.SC_CREATED) {

			} else {
				if (receive.length() <= 0)
					receive.append(response.getStatusLine().getReasonPhrase());
				if (receive.length() > 0)
					Log.v(TAG, receive.toString());
				Log.v(TAG, "nRet=" + nRet + ", url = " + mStrURL);
			}
		} catch (SocketTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_timeout_error;
		} catch (SocketException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_error;
		} catch (ConnectTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_connect_timeout_error;
		} catch (UnknownHostException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_unknown_host_error;
		} catch (Exception e) {
			Log.e(TAG, getErrMsg(e));
			receive.append(getErrMsg(e));
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException ioe) {
					Log.e(TAG, ioe.toString());
				}
			}
		}

		return nRet;
	}

	@Override
	public int doPut(String mStrURL, JSONObject c, StringBuilder receive) {
		return doPut(mStrURL, c.toString(), receive);
	}

	@Override
	public int doPost(String mStrURL, JSONObject c, StringBuilder receive) {
		return doPost(mStrURL, c.toString(), receive);
	}

	@Override
	public int doPost(String url, HttpEntity entity, StringBuilder receive) {
		debug("doPost:"+ url);
		int nRet = R.string.nd_http_error;
		InputStream inputStream = null;
		receive.delete(0, receive.length());
		HttpClient client = null;
		try {
			if(url.contains("https://")){
				client = getHttpsClient();	
			}else {
				client = getHttpClient();
			}

//			// 检查代理设置
//			checkProxy(client);

			HttpPost request = new HttpPost(url);

			setHttpHeader(request);

			request.setEntity(entity);

			// POST and get response code
			HttpResponse response = client.execute(request);
			nRet = response.getStatusLine().getStatusCode();
			// get response string
			inputStream = response.getEntity().getContent();

			Header contentEncoding = response
					.getFirstHeader(HTTP.CONTENT_ENCODING);
			// 判断是否有压缩
			if (contentEncoding != null
					&& contentEncoding.getValue().equalsIgnoreCase(GZIP)) {
				inputStream = new GZIPInputStream(inputStream);
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(
					inputStream));

			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				receive.append(line + NL);
			}

			if (nRet == HttpStatus.SC_OK || nRet == HttpStatus.SC_CREATED) {

			} else {
				if (receive.length() <= 0)
					receive.append(response.getStatusLine().getReasonPhrase());
				if (receive.length() > 0)
					Log.v(TAG, receive.toString());
			}
		} catch (SocketTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_timeout_error;
		} catch (SocketException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_error;
		} catch (ConnectTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_connect_timeout_error;
		} catch (UnknownHostException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_unknown_host_error;
		} catch (Exception e) {
			Log.e(TAG, getErrMsg(e));
			receive.append(getErrMsg(e));
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException ioe) {
					Log.e(TAG, ioe.toString());
				}
			}
		}

		return nRet;
	}

	// 检查代理设置
	private void checkProxy(HttpClient client) {
		HttpHost proxyHost = null;
		// 只有wap才需要设置代理
		if (needToProxy(mContext)) {
			if (Proxy.getDefaultHost() != null) {
				proxyHost = new HttpHost(Proxy.getDefaultHost(),
						Proxy.getDefaultPort());
				if (proxyHost != null) {
					client.getParams().setParameter(
							ConnRoutePNames.DEFAULT_PROXY, proxyHost);
				}
			}
		}
	}

	@Override
	public int doPut(String mStrURL, String content, StringBuilder receive) {
		debug("doPut:"+ mStrURL);
		int nRet = R.string.nd_http_error;
		InputStream inputStream = null;
		receive.delete(0, receive.length());
		try {
			HttpClient client = getHttpClient();

			// 检查代理设置
//			checkProxy(client);

			HttpPut request = new HttpPut(mStrURL);

			setHttpHeader(request);

			// get json string and pass to entigy
			HttpEntity entity;
			// StringEntity s = new
			// StringEntity(StrFun.StringToUnicode(c.toString()), HTTP.UTF_8);
			StringEntity s = new StringEntity(content, HTTP.UTF_8);
			s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
					"application/json"));
			s.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING,
					HTTP.UTF_8));

			entity = s;
			request.setEntity(entity);

			// POST and get response code
			HttpResponse response = client.execute(request);
			nRet = response.getStatusLine().getStatusCode();
			// get response string
			inputStream = response.getEntity().getContent();

			Header contentEncoding = response
					.getFirstHeader(HTTP.CONTENT_ENCODING);
			// 判断是否有压缩
			if (contentEncoding != null
					&& contentEncoding.getValue().equalsIgnoreCase(GZIP)) {
				inputStream = new GZIPInputStream(inputStream);
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(
					inputStream));

			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				receive.append(line + NL);
			}

			if (nRet == HttpStatus.SC_OK || nRet == HttpStatus.SC_CREATED) {

			} else {
				if (receive.length() <= 0)
					receive.append(response.getStatusLine().getReasonPhrase());
				if (receive.length() > 0)
					Log.v(TAG, receive.toString());
				Log.v(TAG, "nRet=" + nRet + ", url = " + mStrURL + ", send="
						+ content);
			}
		} catch (SocketTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_timeout_error;
		} catch (SocketException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_error;
		} catch (ConnectTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_connect_timeout_error;
		} catch (UnknownHostException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_unknown_host_error;
		} catch (Exception e) {
			Log.e(TAG, getErrMsg(e));
			receive.append(getErrMsg(e));
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException ioe) {
					Log.e(TAG, ioe.toString());
				}
			}
		}

		return nRet;
	}

	@Override
	public int doPost(String mStrURL, String content, StringBuilder receive) {
		StringEntity s;
		try {
			s = new StringEntity(content, HTTP.UTF_8);
			s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
					"application/json"));
			s.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING,
					HTTP.UTF_8));
			if(mStrURL.contains("https")){//判读是否是https请求
				try {
					return doPostForHttps(mStrURL, s, receive);
				} catch (Exception e) {//https请求发生异常,要走http请求
					e.printStackTrace();
					mStrURL=mStrURL.replace("https://", "http://");
					return doPost(mStrURL, s, receive);
				}
			}else{
				return doPost(mStrURL, s, receive);
			}
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return 0;

	}
	
	@Override
	public int doUploadImage(String url, Bitmap bitmap, String httpMethod) {
		int nRet = R.string.nd_http_error;
		if (bitmap == null || bitmap.isRecycled()) {
			return nRet;
		}

		Charset charset = Charset.forName("UTF-8");
		MultipartEntity entity = new MultipartEntity(
				HttpMultipartMode.BROWSER_COMPATIBLE, null, charset);
		try {
			entity.addPart("offset", new StringBody(String.valueOf(0)));

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.JPEG, 80, bos);
			ByteArrayBody body = new ByteArrayBody(bos.toByteArray(), "tmp.jpg");
			byte[] data = bos.toByteArray();
			String md5 = MD5ArithmeticUtils.getMD5OfBytes(data);
			entity.addPart("md5", new StringBody(md5));
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			entity.addPart("photo", body);
			entity.addPart("filesize", new StringBody(String.valueOf(body.getContentLength())));
			
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		HttpResponse response = null;
		HttpUriRequest method = null;
		try {
			URI uri = new URI(url);
			// Log.d(TAG, "Sending1 " + httpMethod + " request to " + url);
			method = createMethod(httpMethod, uri, entity);
			setupHTTPConnectionParams(method);
			DefaultHttpClient mClient = new DefaultHttpClient();
			response = mClient.execute(method, new BasicHttpContext());
			nRet = response.getStatusLine().getStatusCode();
		} catch (SocketTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_timeout_error;
		} catch (ClientProtocolException e) {
			Log.e(TAG, getErrMsg(e));
		} catch (IOException e) {
			Log.e(TAG, getErrMsg(e));
		} catch (RuntimeException e) {
			Log.e(TAG, getErrMsg(e));
		} catch (URISyntaxException e) {
            Log.e(TAG, getErrMsg(e));
        } catch (Exception e) {
			Log.e(TAG, getErrMsg(e));
		}
		return nRet;
	}

	/**
	 * @n<b>函数名称</b> :createMethod
	 * @brief 表单方式 上传图片使用
	 * @see
	 * @since Ver 1.3.0
	 * @param @param httpMethod
	 * @param @param uri
	 * @param @param entity
	 * @param @return
	 * @param @throws HttpException
	 * @return HttpUriRequest
	 * @<b>作者</b> : daiyf
	 * @<b>创建时间</b> : 2013-12-13下午3:36:29
	 */
	protected HttpUriRequest createMethod(String httpMethod, URI uri,
			MultipartEntity entity) throws HttpException {
		HttpUriRequest method;

		// HttpPost
		if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
			HttpPost post = new HttpPost(uri);
			post.setEntity(entity);
			method = post;
		}
		// HttpDelete
		else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
			method = new HttpDelete(uri);
		}
		// HttpPut
		else if (httpMethod.equals(HttpPut.METHOD_NAME)) {
			HttpPut put = new HttpPut(uri);
			method = put;
		} else {
			method = new HttpGet(uri);
			Log.v(TAG, "createMethod:" + method.getMethod());
		}
		return method;
	}

	@Override
	public int doDownFile(String mStrURL, File saveFile) {
		debug("doDownFile:"+ mStrURL);
		int nRet = R.string.nd_http_error;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			HttpClient client = getHttpClient();

			// 检查代理设置
//			checkProxy(client);

			HttpGet request = new HttpGet();
			request.setURI(new URI(mStrURL));

			setHttpHeader(request);

			// sending request
			HttpResponse response = client.execute(request);
			nRet = response.getStatusLine().getStatusCode();
			
			// get response code and string
			inputStream = response.getEntity().getContent();
			if (nRet != HttpStatus.SC_OK && nRet != HttpStatus.SC_CREATED) {

				BufferedReader in = new BufferedReader(new InputStreamReader(
						inputStream));
				StringBuilder sb = new StringBuilder();
				String line = "";
				String NL = System.getProperty("line.separator");
				while ((line = in.readLine()) != null) {
					sb.append(line + NL);
				}
				Log.e(TAG, sb.toString());
				return nRet;
			}

			Header contentEncoding = response
					.getFirstHeader(HTTP.CONTENT_ENCODING);
			// 判断是否有压缩
			if (contentEncoding != null
					&& contentEncoding.getValue().equalsIgnoreCase(GZIP)) {
				inputStream = new GZIPInputStream(inputStream);
			}

			// 把文件存到path
			if (saveFile.exists()) {
				saveFile.delete();
			}
			outputStream = new FileOutputStream(saveFile);
			byte buf[] = new byte[1024];
			int byteread = 0;
			while ((byteread = inputStream.read(buf)) != -1) {
				outputStream.write(buf, 0, byteread);
			}

			if (nRet == HttpStatus.SC_OK || nRet == HttpStatus.SC_CREATED) {

			} else {
				Log.v(TAG, "nRet=" + nRet + ", url = " + mStrURL);
			}

		} catch (SocketTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_timeout_error;
		} catch (SocketException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_error;
		} catch (ConnectTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_connect_timeout_error;
		} catch (UnknownHostException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_unknown_host_error;
		} catch (Exception e) {
			if (saveFile.exists()) {
				saveFile.delete();
			}
			Log.e(TAG, getErrMsg(e));
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException ioe) {
					Log.e(TAG, ioe.toString());
				}
			}
			if (outputStream != null)
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}

		return nRet;
	}

	@Override
	public int doPost(String mStrURL, byte[] b, StringBuilder receive) {
		debug("dopost:"+ mStrURL);
		int nRet = R.string.nd_http_error;
		InputStream inputStream = null;
		receive.delete(0, receive.length());
		try {
			HttpClient client = getHttpClient();

//			checkProxy(client);

			HttpPost request = new HttpPost(mStrURL);

			setHttpHeader(request);

			ByteArrayEntity byteArray = new ByteArrayEntity(b);

			request.setEntity(byteArray);
			// POST and get response code
			HttpResponse response = client.execute(request);
			nRet = response.getStatusLine().getStatusCode();
			// get response string
			inputStream = response.getEntity().getContent();

			Header contentEncoding = response
					.getFirstHeader(HTTP.CONTENT_ENCODING);
			// 判断是否有压缩
			if (contentEncoding != null
					&& contentEncoding.getValue().equalsIgnoreCase(GZIP)) {
				inputStream = new GZIPInputStream(inputStream);
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(
					inputStream));

			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				receive.append(line + NL);
			}

			if (nRet == HttpStatus.SC_OK || nRet == HttpStatus.SC_CREATED) {

			} else {
				if (receive.length() <= 0)
					receive.append(response.getStatusLine().getReasonPhrase());
				if (receive.length() > 0)
					Log.v(TAG, receive.toString());
				Log.v(TAG, "nRet=" + nRet + ", url = " + mStrURL);
			}
		} catch (SocketTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_timeout_error;
		} catch (SocketException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_socket_error;
		} catch (ConnectTimeoutException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_connect_timeout_error;
		} catch (UnknownHostException e) {
			Log.e(TAG, getErrMsg(e));
			nRet = R.string.nd_unknown_host_error;
		} catch (Exception e) {
			Log.e(TAG, getErrMsg(e));
			receive.append(getErrMsg(e));
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException ioe) {
					Log.e(TAG, ioe.toString());
				}
			}
		}

		return nRet;
	}
	/**
	 * 用于https请求的方法
	 * @param mStrURL
	 * @param b
	 * @param receive
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws KeyStoreException 
	 * @throws CertificateException 
	 * @throws NoSuchAlgorithmException 
	 * @throws UnrecoverableKeyException 
	 * @throws KeyManagementException 
	 */
	public int doPostForHttps(String url, HttpEntity entity, StringBuilder receive) throws ClientProtocolException, IOException, KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
		debug("doPost:"+ url);
		int nRet = R.string.nd_http_error;
		InputStream inputStream = null;
		receive.delete(0, receive.length());
		try {
			HttpClient client = getHttpsClient();

//			// 检查代理设置
//			checkProxy(client);

			HttpPost request = new HttpPost(url);

			setHttpHeader(request);

			request.setEntity(entity);

			// POST and get response code
			HttpResponse response = client.execute(request);
			nRet = response.getStatusLine().getStatusCode();
			// get response string
			inputStream = response.getEntity().getContent();

			Header contentEncoding = response
					.getFirstHeader(HTTP.CONTENT_ENCODING);
			// 判断是否有压缩
			if (contentEncoding != null
					&& contentEncoding.getValue().equalsIgnoreCase(GZIP)) {
				inputStream = new GZIPInputStream(inputStream);
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(
					inputStream));

			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				receive.append(line + NL);
			}

			if (nRet == HttpStatus.SC_OK || nRet == HttpStatus.SC_CREATED) {

			} else {
				if (receive.length() <= 0)
					receive.append(response.getStatusLine().getReasonPhrase());
				if (receive.length() > 0)
					Log.v(TAG, receive.toString());
			}
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException ioe) {
					Log.e(TAG, ioe.toString());
				}
			}
		}

		return nRet;
	}

	private String getErrMsg(Exception e) {
		String msg = e.getMessage();
		if (msg == null) {
			msg = e.toString();
		}
		return msg;
	}

	// ////////////////////////////////////// 代理控制
	// ///////////////////////////////////////
	private boolean needToProxy(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivityManager == null) {
			return false;
		}

		NetworkInfo info = connectivityManager.getActiveNetworkInfo();
		if (info == null) {
			return false;
		}

		String type = info.getTypeName();

		if (type.equalsIgnoreCase("MOBILE")) { // GPRS方式

			String apnStr = info.getExtraInfo();
			if (apnStr != null) {
				apnStr = apnStr.toLowerCase();
				if (apnStr.contains("wap")) { // WAP方式
					String proxyHost = android.net.Proxy.getDefaultHost();
					if (proxyHost != null && !proxyHost.equals("")) {
						return true;
					}
				}
			}
		}

		return false;
	}

	private HttpClient getNewHttpClient(HttpParams params) {  
        try {  
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
            trustStore.load(null, null);  
            
//            SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);  
//            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
    
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);  
    
            SchemeRegistry registry = new SchemeRegistry();  
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));  
//            registry.register(new Scheme("https", sf, 443));  
    
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);  
    
            return new DefaultHttpClient(ccm, params);  
        } catch (Exception e) {  
            return new DefaultHttpClient();  
        }  
    }  
	
	// 异步下载文件
    public void downloadFile(String mStrUrl, String mSessionId,String saveFilePath, DownloadListener l) {
		
		HttpGet request = new HttpGet();
		try {
			request.setURI(new URI(mStrUrl));
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		request.addHeader(ACCEPT_ENCODEING, GZIP);
		request.addHeader(new BasicHeader("COOKIE", "PHPSESSID=" + mSessionId));
		new DownloadFileTask(request, saveFilePath, l).execute();
	}
	
	public class DownloadFileTask extends AsyncTask<Void, Integer, String> {
		private String mSaveFilePath;
		private DownloadListener mDownloadListener;
		private HttpGet mRequest;

		public DownloadFileTask(HttpGet request, String saveFilePath,
				DownloadListener l) {

			mSaveFilePath = saveFilePath;
			mDownloadListener = l;
			mRequest = request;
		}

		@Override
		protected String doInBackground(Void... params) {
			int nRet = R.string.nd_http_error;
			InputStream inputStream = null;
			OutputStream outputStream = null;
			// 把文件存到path
			File temp = new File(mSaveFilePath + ".tmp");
			if (temp.exists()) {
				temp.delete();
			}
			try {
				// make a get client
				HttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,
						CONNECTION_TIMEOUT_MS);
				HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT_MS);
				HttpClientParams.setRedirecting(httpParams, true);
				HttpClient client = new DefaultHttpClient(httpParams);

				// 检查代理设置
				checkProxy(client);

				// sending request
				HttpResponse response = client.execute(mRequest);
				nRet = response.getStatusLine().getStatusCode();

				// get response code and string
				inputStream = response.getEntity().getContent();
				if (nRet != HttpStatus.SC_OK && nRet != HttpStatus.SC_CREATED) {

					BufferedReader in = new BufferedReader(
							new InputStreamReader(inputStream));
					StringBuilder sb = new StringBuilder();
					String line = "";
					String NL = System.getProperty("line.separator");
					while ((line = in.readLine()) != null) {
						sb.append(line + NL);
					}
					Log.e(TAG, sb.toString());
					return null;
				}

				Header contentEncoding = response
						.getFirstHeader(HTTP.CONTENT_ENCODING);

				// 判断是否有压缩
				if (contentEncoding != null
						&& contentEncoding.getValue().equalsIgnoreCase(GZIP)) {
					inputStream = new GZIPInputStream(inputStream);
				}

				outputStream = new FileOutputStream(temp);
				byte buf[] = new byte[1024];
				int byteread = 0;
				long fileLength = getInstanceLength(response);
				Log.d(TAG, "fileLength:" + fileLength);
				long downloadedFileLength = 0;
				while ((byteread = inputStream.read(buf)) != -1) {
					downloadedFileLength += byteread;
					publishProgress((int) ((float) downloadedFileLength
							/ fileLength * 100));
					Log.d(TAG, "downloadedFileLength:" + downloadedFileLength
							+ " || %"
							+ ((float) downloadedFileLength / fileLength) * 100);
					outputStream.write(buf, 0, byteread);
				}

				if (nRet == HttpStatus.SC_OK || nRet == HttpStatus.SC_CREATED) {
					temp.renameTo(new File(mSaveFilePath));
				}

			} catch (SocketTimeoutException e) {
				Log.e(TAG, getErrMsg(e));
				nRet = R.string.nd_socket_timeout_error;
			} catch (SocketException e) {
				Log.e(TAG, getErrMsg(e));
				nRet = R.string.nd_socket_error;
			} catch (ConnectTimeoutException e) {
				Log.e(TAG, getErrMsg(e));
				nRet = R.string.nd_connect_timeout_error;
			} catch (UnknownHostException e) {
				Log.e(TAG, getErrMsg(e));
				nRet = R.string.nd_unknown_host_error;
			} catch (Exception e) {
				if (temp.exists()) {
					temp.delete();
				}
				Log.e(TAG, getErrMsg(e));
			} finally {
				if (inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException ioe) {
						Log.e(TAG, ioe.toString());
					}
				}
				if (outputStream != null)
					try {
						outputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
			}

			if (nRet != HttpStatus.SC_OK && nRet != HttpStatus.SC_CREATED) {
				return null;
			}

			return mSaveFilePath;
		}

		@Override
		protected void onPostExecute(String result) {
			mDownloadListener.finish(result);
			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			mDownloadListener.updateStatus(values[0]);
			super.onProgressUpdate(values);
		}
	}

	public interface DownloadListener {
		public void updateStatus(int progress);

		public void finish(String path);
	}

	/**
	 * 文件下载的时侯获取文件大小
	 * 
	 * @param response
	 * @return
	 */
	private long getInstanceLength(HttpResponse response) {
		long length = -1;
		if (response != null) {
			Header[] range = response.getHeaders("Content-Range");
			if (range.length > 0) {
				// Get the header value
				String value = range[0].getValue();

				// Split the value
				String[] section = value.split("/");

				try {
					// Parse for the instance length
					length = Long.parseLong(section[1]);
				} catch (NumberFormatException e) {
					// The server returned an unknown "*" or invalid
					// instance-length
					Log.d(TAG,
							String.format(
									"The HttpResponse contains an invalid instance-length: %s",
									value));
				}
			}
		}
		return length;
	}
	
	boolean debuggable=false;
	private void debug(String text){
		if (debuggable){
			Log.d("debug",text);
		}
	}
	
	/**
	 * 设置头部请求代理。
	 * <br>Created 2014-5-20 上午11:42:30
	 * @param agent_ob 代理句柄
	 * @author       suchangjun
	*/
	public void setAgent(ISetHeadAgent agent_ob)
	{
		
	}

    @Override
    public int doDeleteWithEntity(String mStrURL, HttpEntity entity, StringBuilder receive) {
        debug( "dodelete:"+mStrURL);
        int nRet = R.string.nd_http_error;
        InputStream inputStream = null;
        receive.delete(0, receive.length());
        try {
            // make a DELETE client
            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams,
                    CONNECTION_TIMEOUT_MS);
            HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT_MS);
            HttpClientParams.setRedirecting(httpParams, true);
            HttpClient client = getNewHttpClient(httpParams);

            // 检查代理设置
//          checkProxy(client);

            HttpEntityDelete request = new HttpEntityDelete(mStrURL);

            setHttpHeader(request);
            
            request.setEntity(entity);
            
            // POST and get response code
            HttpResponse response = client.execute(request);
            nRet = response.getStatusLine().getStatusCode();
            // get response string
            inputStream = response.getEntity().getContent();

            Header contentEncoding = response
                    .getFirstHeader(HTTP.CONTENT_ENCODING);
            // 判断是否有压缩
            if (contentEncoding != null
                    && contentEncoding.getValue().equalsIgnoreCase(GZIP)) {
                inputStream = new GZIPInputStream(inputStream);
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    inputStream));

            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                receive.append(line + NL);
            }

            if (nRet == HttpStatus.SC_OK || nRet == HttpStatus.SC_CREATED) {

            } else {
                if (receive.length() <= 0)
                    receive.append(response.getStatusLine().getReasonPhrase());
                if (receive.length() > 0)
                    Log.v(TAG, receive.toString());
                Log.v(TAG, "nRet=" + nRet + ", url = " + mStrURL);
            }
        } catch (SocketTimeoutException e) {
            Log.e(TAG, getErrMsg(e));
            nRet = R.string.nd_socket_timeout_error;
        } catch (SocketException e) {
            Log.e(TAG, getErrMsg(e));
            nRet = R.string.nd_socket_error;
        } catch (ConnectTimeoutException e) {
            Log.e(TAG, getErrMsg(e));
            nRet = R.string.nd_connect_timeout_error;
        } catch (UnknownHostException e) {
            Log.e(TAG, getErrMsg(e));
            nRet = R.string.nd_unknown_host_error;
        } catch (Exception e) {
            Log.e(TAG, getErrMsg(e));
            receive.append(getErrMsg(e));
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ioe) {
                    Log.e(TAG, ioe.toString());
                }
            }
        }

        return nRet;
    }
}
